package com.zp.drug.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zp.common.core.utils.StringUtils;
import com.zp.common.myBatis.core.page.PageQuery;
import com.zp.common.myBatis.core.page.TableDataInfo;
import com.zp.drug.entity.DrugPresPermissionsConf;
import com.zp.drug.entity.bo.DrugPresPermissionsConfBo;
import com.zp.drug.entity.vo.DrugPresPermissionsConfVo;
import com.zp.drug.mapper.DrugPresPermissionsConfMapper;
import com.zp.drug.service.IDrugPresPermissionsConfService;
import com.zp.system.api.RemoteUserService;
import com.zp.system.api.entity.SysUser;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 处方权限配置Service业务层处理
 *
 * @author zhang peng
 * @ date 2023-06-19
 */
@RequiredArgsConstructor
@Service
public class DrugPresPermissionsConfServiceImpl implements IDrugPresPermissionsConfService {

    private final DrugPresPermissionsConfMapper baseMapper;

    @DubboReference
    private RemoteUserService apiUserService;

    /**
     * 查询处方权限配置
     */
    @Override
    public DrugPresPermissionsConfVo queryById (String id) {
        DrugPresPermissionsConfBo bo = new DrugPresPermissionsConfBo();
        bo.setPermissionsConfId(id);
        DrugPresPermissionsConfVo vo = baseMapper.selectVoList(bo);
        // 获取用户信息
        bo.setUserId(vo.getUserId());
        List<SysUser> userList = getSysUserInfoList(bo);
        // 设置vo中与用户能匹配上的信息
        setVoInfo(userList, vo);
        return vo;
    }

    /**
     * 查询处方权限配置列表(分页)
     */
    @Override
    public TableDataInfo<DrugPresPermissionsConfVo> queryPageList (DrugPresPermissionsConfBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<DrugPresPermissionsConf> lqw = buildQueryWrapper(bo);
        // 获取用户信息
        List<SysUser> userList = getSysUserInfoList(bo);
        List<String> userIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(userList)) {
            if (StringUtils.isNotBlank(userList.get(0).getExceptionCode())) {
                throw new RuntimeException(userList.get(0).getExceptionCode());
            }
            userIds = userList.stream().map(SysUser::getUserId).collect(Collectors.toList());
        } else {
            throw new RuntimeException("未查询到有效用户，请联系管理员");
        }
        bo.setUserIds(userIds);
        Page<DrugPresPermissionsConfVo> result = baseMapper.selectVoList(pageQuery.build(), bo);
        result.getRecords().forEach(item -> {
            // 设置vo中与用户能匹配上的信息
            setVoInfo(userList, item);
        });
        return TableDataInfo.build(result);
    }

    /**
     * 设置vo中与用户能匹配上的信息
     *
     * @param userList 用户list
     * @param vo       处方权限对象
     */
    public void setVoInfo (List<SysUser> userList, DrugPresPermissionsConfVo vo) {
        userList.forEach(userItem -> {
            if (StringUtils.equals(vo.getUserId(), userItem.getUserId())) {
                vo.setNickName(userItem.getNickName());
                vo.setUserName(userItem.getUserName());
                vo.setCertificateNo(userItem.getCertificateNo());
                vo.setCustomerType(userItem.getCustomerType());
            }
        });
    }

    /**
     * 获取用户信息
     *
     * @param bo
     * @return
     */
    public List<SysUser> getSysUserInfoList (DrugPresPermissionsConfBo bo) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(bo.getUserId());
        sysUser.setNickName(bo.getNickName());
        sysUser.setUserName(bo.getUserName());
        sysUser.setCertificateNo(bo.getCertificateNo());
        sysUser.setCustomerType(bo.getCustomerType());
        sysUser.setOrgId(bo.getOrgId());
        sysUser.setDeptId(bo.getDeptId());
        // 获取人员信息集合
        return apiUserService.getUserList(sysUser);
    }

    /**
     * 查询处方权限配置列表(不分页)
     */
    @Override
    public List<DrugPresPermissionsConfVo> queryList (DrugPresPermissionsConfBo bo) {
        LambdaQueryWrapper<DrugPresPermissionsConf> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<DrugPresPermissionsConf> buildQueryWrapper (DrugPresPermissionsConfBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<DrugPresPermissionsConf> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getUserId()), DrugPresPermissionsConf::getUserId, bo.getUserId());
        lqw.eq(StringUtils.isNotBlank(bo.getToxiProperty()), DrugPresPermissionsConf::getToxiProperty, bo.getToxiProperty());
        lqw.eq(StringUtils.isNotBlank(bo.getLimitClass()), DrugPresPermissionsConf::getLimitClass, bo.getLimitClass());
        lqw.eq(StringUtils.isNotBlank(bo.getOrgId()), DrugPresPermissionsConf::getOrgId, bo.getOrgId());
        lqw.eq(StringUtils.isNotBlank(bo.getRemarks()), DrugPresPermissionsConf::getRemarks, bo.getRemarks());
        return lqw;
    }

    /**
     * 新增处方权限配置
     */
    @Override
    public Boolean insertByBo (DrugPresPermissionsConfBo bo) {
        DrugPresPermissionsConf add = BeanUtil.toBean(bo, DrugPresPermissionsConf.class);
        validEntityBeforeSave(add);
        add.initEntity();
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setPermissionsConfId(add.getPermissionsConfId());
        }
        return flag;
    }

    /**
     * 修改处方权限配置
     */
    @Override
    public Boolean updateByBo (DrugPresPermissionsConfBo bo) {
        DrugPresPermissionsConf update = BeanUtil.toBean(bo, DrugPresPermissionsConf.class);
        update.updateInfo();
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave (DrugPresPermissionsConf entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除处方权限配置
     */
    @Override
    public Boolean deleteWithValidByIds (Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    /**
     * 同步机构人员
     *
     * @param orgId
     * @return
     */
    @Override
    public Boolean syncOrgPerson (String orgId) {
        List<String> stringList = new ArrayList<>();
        // 查询本机构已存在的用户
        List<DrugPresPermissionsConf> list = baseMapper.selectList(Wrappers.<DrugPresPermissionsConf>lambdaQuery()
                .eq(DrugPresPermissionsConf::getOrgId, orgId));
        if (CollectionUtils.isNotEmpty(list)) {
            stringList = list.stream().map(DrugPresPermissionsConf::getUserId).collect(Collectors.toList());
        }
        // 查询本机构没用增加处方权限的人员信息
        SysUser sysUser = new SysUser();
        sysUser.setOrgId(orgId);
        sysUser.setExistUserIds(stringList);
        List<SysUser> userList = apiUserService.getUserList(sysUser);
        userList = userList.stream().filter(item->StringUtils.isNotBlank(item.getOrgId())).collect(Collectors.toList());
        List<DrugPresPermissionsConf> newData = new ArrayList<>();
        userList.forEach(item -> {
            DrugPresPermissionsConf insertData = new DrugPresPermissionsConf();
            insertData.initEntity();
            insertData.setUserId(item.getUserId());
            insertData.setOrgId(orgId);
            newData.add(insertData);
        });
        if (CollectionUtils.isNotEmpty(newData)) {
            return baseMapper.insertBatch(newData);
        }
        return true;
    }
}
